package com.flick.user.ctrl;

import com.flick.annotation.AutoResult;
import com.flick.annotation.NotAutoResult;
import com.flick.common.Result;
import com.flick.exception.CommonException;
import com.flick.po.User;
import com.flick.user.services.UserService;
import com.flick.util.VoUtil;
import com.flick.vo.payment.UserVo;
import com.google.common.collect.ImmutableMap;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "用户相关")
@RequestMapping("/api/user")
@Slf4j
@AutoResult
@DefaultProperties(defaultFallback = "globalFallbackMethod")
public class UserCtrl {

    @Autowired
    UserService service;

    @ApiOperation("测试方法1")
    @GetMapping
    public String pay(@ApiParam(value="ID",defaultValue = "123") @RequestParam String id){
        if(id == null || "".equals(id)) id = "123";
        if("0".equals(id)) throw new CommonException("参数不能为0");
        return id;
    }

    @ApiOperation("测试Array")
    @GetMapping("/order")
    public String[] order(@ApiParam(value="ID",defaultValue = "4,5,6") @RequestParam String id){
        if(id == null || "".equals(id)) id = "4,5,6";
        log.info("测试方法2");
        return id.split(",");
    }

    @ApiOperation("测试map")
    @GetMapping("/map")
    public Map map(){
        Map map = ImmutableMap.of(1,"A",2,"B",3,"C",4,"D");
        return map;
    }

    @ApiOperation("测试列表")
    @GetMapping("/list")
    public List list(){
        return VoUtil.listToVo(service.list(), UserVo.class);
    }

    @ApiOperation("测试分页")
    @GetMapping("/page")
    public Page<User> page(@ApiParam(value="page",defaultValue = "1",required = true,example = "1") @RequestParam Integer page,
                           @ApiParam(value="size",defaultValue = "10",required = true,example = "10") @RequestParam Integer size){
        Page res = VoUtil.pageToVo(service.page(page,size), UserVo.class);
        return res;
    }

    @ApiOperation("测试保存(默认3秒)")
    @PostMapping()
    @NotAutoResult  //因为结果为Result对象,此方法不经过AOP转换,避免性能消耗
    @HystrixCommand
    public Result save(@ApiParam(value="sec",defaultValue = "3",required = true,example = "3") @RequestParam Integer sec){
        return service.save( + sec);
    }

    public Result globalFallbackMethod(){
        return new Result<String>("500","服务出现降级,启动全局降级设置,请稍后再试");
    }


}
